package cn.ltgodm.template.web.controller.auth;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import cn.ltgodm.template.common.constant.CacheConstants;
import cn.ltgodm.template.common.constant.Constants;
import cn.ltgodm.template.common.domain.AjaxResult;
import cn.ltgodm.template.common.utils.RedisCache;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.google.code.kaptcha.Producer;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/auth")
@Tag(name = "验证码")
@ApiSupport(author = "ltgodm")
public class CaptchaController
{

    @Resource(name = "captchaProducer")
    private Producer producer;

    @Resource(name = "captchaProducerMath")
    private Producer producerMath;

    @Autowired
    private RedisCache redisCache;

    @Value("${user.captcha.type:math}")
    private String captchaType;

    @Value("${user.captcha.enable}")
    private boolean captchaEnable;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    @Operation(summary = "生成验证码")
    public AjaxResult getCode(HttpServletResponse response) throws IOException {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("captchaEnabled",captchaEnable);
        if (!captchaEnable){
            return ajax;
        }
        //保存验证码信息
        String uuid = IdUtil.simpleUUID();
        String verityKey = CacheConstants.CAPTCHA_CODE_KEY +uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        //生成验证码
        if ("math".equals(captchaType)){
            //数学验证码
            String capTest = producerMath.createText();
            capStr = capTest.substring(0,capTest.lastIndexOf("@"));
            code =capTest.substring(capTest.lastIndexOf("@")+1);
            image =producerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = producer.createText();
            image = producer.createImage(capStr);
        }

        //缓存验证码,存活时间2分钟
        redisCache.setCacheObject(verityKey,code,Constants.CAPTCHA_EXPIRATION,TimeUnit.MINUTES);
        //创建输入流转换信息
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return AjaxResult.error(e.getMessage());
        }
        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }
}
